<!--个人中心-->
<template>
  <div class="container">
    <div class="clearfix">
      <h3>个人中心</h3>
    </div>
<!--    展示个人信息-->
    <el-form label-position="left" label-width="100px" class="info-form">
      <el-form-item label="账号">
        <el-input v-model="userInfo.account" readonly />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="userInfo.name" readonly />
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="userInfo.facultyName" readonly />
      </el-form-item>
      <el-form-item label="专业">
        <el-input v-model="userInfo.majorName" readonly />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" readonly />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="userInfo.phone" readonly />
      </el-form-item>
      <el-form-item label="指导教师1">
        <el-input
            :value="userInfo.teacher1Account && userInfo.teacher1Name
           ? `${userInfo.teacher1Account} - ${userInfo.teacher1Name}`
           : ''"
            readonly
        />
      </el-form-item>
      <el-form-item label="指导教师2">
        <el-input
            :value="userInfo.teacher2Account && userInfo.teacher2Name
           ? `${userInfo.teacher2Account} - ${userInfo.teacher2Name}`
           : ''"
            readonly
        />
      </el-form-item>
    </el-form>

<!--    按钮-->
    <div class="operation-btns">
      <el-button
          type="primary"
          @click="passwordDialog = true"
          class="recover"
      >
        修改密码
      </el-button>
      <el-button
          @click="handleLogout"
          class="delete"
      >
        退出登录
      </el-button>
    </div>

<!-- 密码修改弹窗 -->
    <el-dialog
        v-model="passwordDialog"
        title="修改密码"
        width="500px"
        @closed="resetPasswordForm"
    >
      <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
              placeholder="请输入当前密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
              placeholder="不少于6位字符"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="passwordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPassword" class="footer-button">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { getAccount } from "../api/login.js";
import {getUserInfoByAccount, updatePassword} from "../api/person.js";

const router = useRouter()

// 用户账号
const account = ref(null);

// 单个用户信息对象
const userInfo = ref({
  id:'',
  account: '',
  name: '',
  facultyName: '',
  majorName: '',
  email: '',
  phone: '',
  teacher1Account: '',
  teacher2Account: '',
  teacher1Name: '',
  teacher2Name: ''
})

const passwordDialog = ref(false) // 密码弹窗控制
const passwordFormRef = ref() // 表单引用

// 密码表单结构
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '长度应不少于6位字符', trigger: 'blur' },
    { max: 20, message: '长度不得超过20位字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户账号
const fetchAccount = async () => {
  try {
    const response = await getAccount();
    account.value = response.data;  // 保存用户账号
  } catch (error) {
    console.error('获取用户账号失败:', error);
  }
};

// 提交修改密码
const submitPassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      const res = await updatePassword({
        account: account.value,
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      })
      if (res.code === 1) {
        ElMessage.success('密码修改成功')
        passwordDialog.value = false
        resetPasswordForm()
        ElMessage.success('即将在3秒后退出登录，返回登录界面')
        setTimeout(() => {
          handleLogout()
        }, 3000)
      } else {
        throw new Error(res.msg || '密码修改失败')
      }
    } catch (error) {
      ElMessage.error(error.msg)
    }
  })
}

// 重置表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 加载用户信息
const loadUserInfo = () => {
  if (!account) {
    ElMessage.error('未获取到用户信息')
    return
  }
  getUserInfoByAccount({
    account: account.value
  }).then(res => {
    if (res.code === 1) {
      userInfo.value = res.data
      localStorage.setItem('userId', res.data.id)
      console.log(userInfo.value)
      console.log(res.data.id)

    } else {
      ElMessage.error('用户信息加载失败')
    }
  })
}

// 退出登录方法
const handleLogout = () => {
  // 清除所有认证相关存储
  localStorage.removeItem('pinia-token');
  // 跳转到登录页
  router.push('/login')
  // 提示信息
  ElMessage.success('已退出登录')
}

onMounted(async () => {
  await fetchAccount();  // 先获取账号
  loadUserInfo();         // 再加载用户信息
});
</script>



<style scoped>
.container {
  padding: 30px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 8px 30px rgba(58, 194, 159, 0.1);
  margin: 20px;
  min-height: 70vh;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;
}

.clearfix h3 {
  color: rgb(48, 49, 51);
  font-size: 24px;
  margin: 0;
  text-shadow: 1px 1px 2px rgba(58, 194, 159, 0.2);
  position: relative;
  padding-left: 20px;
}

.clearfix h3::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 70%;
  background: linear-gradient(180deg, #3ac29f 0%, #3a7bd5 100%);
  border-radius: 2px;
}

.info-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266 !important;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 2px 6px rgba(58, 194, 159, 0.1);
  background: #f8fafc;
}

.role-tag {
  margin-right: 8px;
  border-radius: 8px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #3ac29f30 0%, #3a7bd530 100%);
  color: #3a7bd5;
  border: none;
}

.operation-btns {
  margin-top: 30px;
  text-align: center;
}

.modify-btn {
  background: linear-gradient(135deg, #3ac29f 0%, #3a7bd5 100%);
  border: none;
  border-radius: 12px;
  padding: 15px 30px;
  color: white;
  transition: all 0.3s;
}

.modify-btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(58, 194, 159, 0.3);
}

.footer-button {
  background: linear-gradient(135deg, #3ac29f 0%, #3a7bd5 100%);
  border: none;
  border-radius: 12px;
  color: white !important;
  padding: 12px 28px;
  transition: all 0.3s ease;
}

.footer-button:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(58, 194, 159, 0.3);
}

.logout-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff4757 100%);
  border: none;
  border-radius: 12px;
  padding: 15px 30px;
  color: white;
  transition: all 0.3s;
  margin-left: 20px;
}

.logout-btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
}

@media (max-width: 768px) {
  .container {
    margin: 10px;
    padding: 20px;
  }

  .info-form {
    padding: 10px;
  }
}
</style>